<template>
  <div class="monitor-view">
    <!-- 任务列表 -->
    <el-card class="task-list-section">
      <template #header>
        <div class="section-title">📋 任务列表</div>
      </template>
      
      <el-table :data="taskList" style="width: 100%" v-loading="isLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="platform" label="平台">
          <template #default="scope">
            <div class="platform-info">
              <span class="platform-icon">{{ getPlatformIcon(scope.row.platform) }}</span>
              <span>{{ getPlatformName(scope.row.platform) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="keywords" label="关键词" show-overflow-tooltip />
        <el-table-column prop="crawlerType" label="爬取类型" width="120">
          <template #default="scope">
            {{ getCrawlerTypeName(scope.row.crawlerType) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status) as any" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="180">
          <template #default="scope">
            <div class="progress-cell">
              <el-progress 
                :percentage="scope.row.progress" 
                :stroke-width="5" 
                :text-inside="true" 
                :format="percentFormat"
                :status="getProgressStatus(scope.row.status)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                v-if="scope.row.status === 'running'"
                type="warning" 
                size="small" 
                @click="pauseTask(scope.row.id)"
                :disabled="isActionLoading"
              >
                暂停
              </el-button>
              <el-button 
                v-if="scope.row.status === 'paused'"
                type="success" 
                size="small" 
                @click="resumeTask(scope.row.id)"
                :disabled="isActionLoading"
              >
                继续
              </el-button>
              <el-button 
                v-if="['running', 'paused'].includes(scope.row.status)"
                type="danger" 
                size="small" 
                @click="stopTask(scope.row.id)"
                :disabled="isActionLoading"
              >
                停止
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="viewTaskDetails(scope.row.id)"
              >
                详情
              </el-button>
              <el-button 
                v-if="scope.row.status === 'completed' || scope.row.status === 'failed' || scope.row.status === 'stopped'"
                type="info" 
                size="small" 
                @click="viewTaskLogs(scope.row.id)"
              >
                日志
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="empty-placeholder" v-if="taskList.length === 0 && !isLoading">
        <el-empty description="暂无任务，请在配置页面提交新任务">
          <el-button type="primary" @click="goToConfig">创建任务</el-button>
        </el-empty>
      </div>
    </el-card>
    
    <!-- 任务详情弹窗 -->
    <el-dialog
      v-model="taskDetailDialogVisible"
      title="任务详情"
      width="80%"
      destroy-on-close
    >
      <div v-if="selectedTask" class="task-detail-dialog">
        <div class="task-header">
          <div class="task-title">
            <span class="platform-icon">{{ getPlatformIcon(selectedTask.platform) }}</span>
            <span>{{ selectedTask.taskName || `${getPlatformName(selectedTask.platform)}-${selectedTask.keywords}` }}</span>
          </div>
          <el-tag :type="getStatusType(selectedTask.status) as any" size="small">
            {{ getStatusText(selectedTask.status) }}
          </el-tag>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="任务ID">{{ selectedTask.id }}</el-descriptions-item>
          <el-descriptions-item label="平台">{{ getPlatformName(selectedTask.platform) }}</el-descriptions-item>
          <el-descriptions-item label="关键词">{{ selectedTask.keywords }}</el-descriptions-item>
          <el-descriptions-item label="爬取类型">{{ getCrawlerTypeName(selectedTask.crawlerType) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ selectedTask.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ selectedTask.startedAt || '未开始' }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ selectedTask.completedAt || '未完成' }}</el-descriptions-item>
          <el-descriptions-item label="目标数量">{{ selectedTask.targetCount }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="task-progress-section">
          <div class="section-title">进度详情</div>
          <el-progress 
            :percentage="selectedTask.progress" 
            :status="getProgressStatus(selectedTask.status)"
          />
          
          <div class="stats-grid">
            <div class="stat-card success">
              <div class="stat-value">{{ selectedTask.successCount }}</div>
              <div class="stat-label">成功</div>
            </div>
            <div class="stat-card danger">
              <div class="stat-value">{{ selectedTask.failedCount }}</div>
              <div class="stat-label">失败</div>
            </div>
            <div class="stat-card warning">
              <div class="stat-value">{{ selectedTask.skippedCount }}</div>
              <div class="stat-label">跳过</div>
            </div>
            <div class="stat-card primary">
              <div class="stat-value">{{ selectedTask.targetCount - selectedTask.crawledCount }}</div>
              <div class="stat-label">剩余</div>
            </div>
          </div>
        </div>
        
        <div class="task-logs-section">
          <div class="section-title">任务日志</div>
          <div class="log-container" ref="taskLogContainer">
            <div v-if="taskLogs.length === 0" class="empty-logs">
              暂无日志记录
            </div>
            <div 
              v-for="(log, index) in taskLogs" 
              :key="index" 
              class="log-item"
              :class="getLogLevel(log.message)"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskDetailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedTask && ['running', 'paused'].includes(selectedTask.status)"
            type="danger" 
            @click="stopTaskFromDialog"
          >
            停止任务
          </el-button>
          <el-button 
            v-if="selectedTask && selectedTask.status === 'completed'"
            type="primary" 
            @click="viewTaskResults"
          >
            查看结果
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 任务日志弹窗 -->
    <el-dialog
      v-model="taskLogDialogVisible"
      title="任务日志"
      width="80%"
      destroy-on-close
    >
      <div class="task-logs-fullscreen">
        <div class="log-controls">
          <el-button size="small" @click="refreshTaskLogs">刷新</el-button>
          <el-button size="small" @click="exportTaskLogs">导出日志</el-button>
        </div>
        <div class="log-container full-height" ref="fullLogContainer">
          <div v-if="taskLogs.length === 0" class="empty-logs">
            暂无日志记录
          </div>
          <div 
            v-for="(log, index) in taskLogs" 
            :key="index" 
            class="log-item"
            :class="getLogLevel(log.message)"
          >
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { getTaskList, getTaskById, pauseTask as apiPauseTask, resumeTask as apiResumeTask, stopTask as apiStopTask, getTaskLogs, exportTaskLogs } from '@/api/crawler'

const router = useRouter()
const appStore = useAppStore()

// 任务列表数据
const taskList = ref<any[]>([])
const isLoading = ref(false)
const isActionLoading = ref(false)

// 任务详情弹窗
const taskDetailDialogVisible = ref(false)
const selectedTask = ref<any>(null)
const taskLogs = ref<any[]>([])
const taskLogDialogVisible = ref(false)
const taskLogContainer = ref<HTMLElement | null>(null)
const fullLogContainer = ref<HTMLElement | null>(null)

// 获取任务列表
const fetchTaskList = async () => {
  isLoading.value = true
  try {
    console.log('开始获取任务列表...')
    
    // 使用try-catch包装API调用，以便捕获和记录详细错误
    let tasks;
    try {
      tasks = await getTaskList()
      console.log('获取到的原始任务列表:', tasks)
    } catch (error) {
      console.error('获取任务列表API调用失败:', error)
      ElMessage.error(`获取任务列表失败: ${error}`)
      isLoading.value = false
      return
    }
    
    // 检查返回的数据类型
    console.log('任务列表数据类型:', typeof tasks)
    if (tasks === null || tasks === undefined) {
      console.warn('任务列表为空或未定义')
      taskList.value = []
      isLoading.value = false
      return
    }
    
    // 处理任务数据，确保字段名称匹配
    const processedTasks = Array.isArray(tasks) ? tasks.map(task => {
      console.log('处理任务:', task)
      
      // 将后端返回的字段名转换为前端使用的驼峰命名
      const processedTask = {
        id: task.id || '',
        name: task.name || '未命名任务',
        platform: task.platform || 'unknown',
        keywords: task.keywords || '',
        crawlerType: task.task_type || 'search', // 转换字段名
        status: task.status || 'pending',
        progress: typeof task.progress === 'number' ? task.progress : 0,
        crawledCount: task.total_count || 0,
        successCount: task.success_count || 0,
        failedCount: task.failed_count || 0,
        targetCount: task.total_count > 0 ? task.total_count : 100, // 如果没有总数，默认为100
        createdAt: task.created_at || new Date().toISOString(),
        startedAt: task.started_at || null,
        completedAt: task.completed_at || null,
        errorMessage: task.error_message || null,
        speed: 0, // 默认速度
        successRate: task.total_count > 0 ? 
          Math.round((task.success_count / task.total_count) * 100) : 0,
        skippedCount: 0, // 默认跳过数
      }
      
      return processedTask
    }) : [];
    
    console.log('处理后的任务列表:', processedTasks)
    taskList.value = processedTasks
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    isLoading.value = false
  }
}

// 工具函数
const getPlatformIcon = (platform: string) => {
  const iconMap: Record<string, string> = {
    xhs: '🔴',
    douyin: '🎵',
    kuaishou: '⚡',
    bilibili: '📺',
    weibo: '📱',
    zhihu: '🗣️',
  }
  return iconMap[platform] || '📱'
}

const getPlatformName = (platform: string) => {
  const platformMap: Record<string, string> = {
    xhs: '小红书',
    douyin: '抖音',
    kuaishou: '快手',
    bilibili: 'B站',
    weibo: '微博',
    zhihu: '知乎',
  }
  return platformMap[platform] || platform
}

const getCrawlerTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    search: '关键词搜索',
    detail: '指定帖子',
    creator: '创作者主页',
  }
  return typeMap[type] || type
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '等待中',
    running: '运行中',
    paused: '已暂停',
    completed: '已完成',
    failed: '失败',
    stopped: '已停止',
  }
  return statusMap[status] || status
}

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'info',
    running: 'success',
    paused: 'warning',
    completed: 'success',
    failed: 'danger',
    stopped: 'info',
  }
  return typeMap[status] || 'info'
}

const getStatusDotClass = (status: string) => {
  const classMap: Record<string, string> = {
    pending: 'info',
    running: 'success',
    paused: 'warning',
    completed: 'success',
    failed: 'danger',
    stopped: 'info',
  }
  return classMap[status] || 'info'
}

const getProgressStatus = (status: string) => {
  if (status === 'completed') return 'success'
  if (status === 'failed') return 'exception'
  if (status === 'paused') return 'warning'
  return ''
}

const percentFormat = (percentage: number) => {
  return percentage.toFixed(0) + '%'
}


const getLogLevel = (message: string) => {
  if (!message) return ''
  if (message.toLowerCase().includes('error') || message.toLowerCase().includes('失败')) return 'error'
  if (message.toLowerCase().includes('warning') || message.toLowerCase().includes('警告')) return 'warning'
  if (message.toLowerCase().includes('success') || message.toLowerCase().includes('成功')) return 'success'
  if (message.toLowerCase().includes('info') || message.toLowerCase().includes('信息')) return 'info'
  return ''
}

// 任务操作函数
const pauseTask = async (taskId: string) => {
  isActionLoading.value = true
  try {
    await apiPauseTask(taskId)
    ElMessage.warning('任务已暂停')
    fetchTaskList() // 刷新任务列表
  } catch (error) {
    console.error('暂停任务失败:', error)
    ElMessage.error(`暂停失败: ${error}`)
  } finally {
    isActionLoading.value = false
  }
}

const resumeTask = async (taskId: string) => {
  isActionLoading.value = true
  try {
    await apiResumeTask(taskId)
    ElMessage.success('任务已恢复')
    fetchTaskList() // 刷新任务列表
  } catch (error) {
    console.error('恢复任务失败:', error)
    ElMessage.error(`恢复失败: ${error}`)
  } finally {
    isActionLoading.value = false
  }
}

const stopTask = async (taskId: string) => {
  try {
    await ElMessageBox.confirm('确定要停止当前任务吗？', '确认停止', {
      type: 'warning',
    })
    
    isActionLoading.value = true
    await apiStopTask(taskId)
    ElMessage.success('任务已停止')
    fetchTaskList() // 刷新任务列表
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止任务失败:', error)
      ElMessage.error(`停止失败: ${error}`)
    }
  } finally {
    isActionLoading.value = false
  }
}

const viewTaskDetails = async (taskId: string) => {
  currentTaskId.value = taskId
  const task = taskList.value.find(t => t.id === taskId)
  if (task) {
    currentTask.value = task
    selectedTask.value = task
    taskDetailDialogVisible.value = true
    
    // 获取任务日志
    await fetchTaskLogs(taskId)
  }
}

const viewTaskLogs = async (taskId: string) => {
  currentTaskId.value = taskId
  await fetchTaskLogs(taskId)
  taskLogDialogVisible.value = true
  
  // 自动滚动到底部
  nextTick(() => {
    if (fullLogContainer.value) {
      fullLogContainer.value.scrollTop = fullLogContainer.value.scrollHeight
    }
  })
}

const fetchTaskLogs = async (taskId: string) => {
  try {
    const logs = await getTaskLogs(taskId)
    taskLogs.value = logs as any[]
    
    // 自动滚动到底部
    nextTick(() => {
      if (taskLogContainer.value) {
        taskLogContainer.value.scrollTop = taskLogContainer.value.scrollHeight
      }
    })
  } catch (error) {
    console.error('获取任务日志失败:', error)
    ElMessage.error('获取任务日志失败')
    taskLogs.value = []
  }
}

const refreshTaskLogs = async () => {
  if (currentTaskId.value) {
    await fetchTaskLogs(currentTaskId.value)
    ElMessage.success('日志已刷新')
  }
}

const exportTaskLogs = async () => {
  if (!currentTaskId.value || taskLogs.value.length === 0) {
    ElMessage.warning('没有可导出的日志')
    return
  }
  
  try {
    const taskId = currentTaskId.value
    const task = taskList.value.find(t => t.id === taskId)
    const fileName = `task_${taskId}_logs_${new Date().toISOString().replace(/:/g, '-')}.txt`
    
    await exportTaskLogs(taskId, fileName)
    ElMessage.success(`日志已导出到: ${fileName}`)
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  }
}

const stopTaskFromDialog = async () => {
  if (!selectedTask.value) return
  
  try {
    await ElMessageBox.confirm('确定要停止当前任务吗？', '确认停止', {
      type: 'warning',
    })
    
    isActionLoading.value = true
    const { invoke } = await import('@tauri-apps/api/core')
    await invoke('stop_task', { taskId: selectedTask.value.id })
    ElMessage.success('任务已停止')
    
    // 刷新任务列表和详情
    await fetchTaskList()
    if (selectedTask.value) {
      const updatedTask = taskList.value.find(t => t.id === selectedTask.value.id)
      if (updatedTask) {
        selectedTask.value = updatedTask
      }
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止任务失败:', error)
      ElMessage.error(`停止失败: ${error}`)
    }
  } finally {
    isActionLoading.value = false
  }
}

const viewTaskResults = () => {
  if (!selectedTask.value) return
  
  // 跳转到数据页面，并传递任务ID作为过滤条件
  router.push({
    path: '/data',
    query: { 
      taskId: selectedTask.value.id,
      platform: selectedTask.value.platform,
      keywords: selectedTask.value.keywords
    }
  })
}

const goToConfig = () => {
  router.push('/config')
}

// 轮询任务状态
let statusTimer: NodeJS.Timeout | null = null

const startStatusPolling = () => {
  // 每3秒刷新一次任务列表
  statusTimer = setInterval(fetchTaskList, 3000)
}

const stopStatusPolling = () => {
  if (statusTimer) {
    clearInterval(statusTimer)
    statusTimer = null
  }
}

// 组件生命周期
onMounted(() => {
  fetchTaskList()
  startStatusPolling()
})

onUnmounted(() => {
  stopStatusPolling()
})
</script>

<style scoped>
.monitor-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.task-list-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.platform-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.platform-icon {
  font-size: 16px;
}

.progress-cell {
  width: 100%;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.empty-placeholder {
  padding: 30px 0;
}

/* 任务详情弹窗样式 */
.task-detail-dialog {
  padding: 10px 0;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.task-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.task-progress-section, .task-logs-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-top: 15px;
}

.stat-card {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
  background: #f5f7fa;
}

.stat-card.success { background: #f0f9ff; color: #67c23a; }
.stat-card.danger { background: #fef0f0; color: #f56c6c; }
.stat-card.warning { background: #fdf6ec; color: #e6a23c; }
.stat-card.primary { background: #ecf5ff; color: #409eff; }

.log-container {
  height: 300px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
  font-family: 'Courier New', monospace;
}

.log-container.full-height {
  height: 500px;
}

.log-item {
  margin-bottom: 5px;
  font-size: 12px;
  line-height: 1.4;
}

.log-time {
  color: #909399;
  margin-right: 8px;
}

.log-message {
  color: #303133;
}

.log-item.error .log-message { color: #f56c6c; }
.log-item.warning .log-message { color: #e6a23c; }
.log-item.success .log-message { color: #67c23a; }
.log-item.info .log-message { color: #409eff; }

.empty-logs {
  text-align: center;
  color: #909399;
  font-style: italic;
  padding: 20px;
}

.log-controls {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 10px;
}

.task-logs-fullscreen {
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .monitor-view {
    padding: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
